package com.midipad;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
 * credits goes to plusminus for this tutorial that I adapted
 * http://www.anddev.org/building_an_android_filebrowser_list-based_-t67.html
 * @author Tim
 * 
 */
public class FileBrowser extends ListActivity {
	private List<String> directoryEntries = new ArrayList<String>();
    private File currentDirectory = new File("/"); 
    private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; }
    private final DISPLAYMODE displayMode = DISPLAYMODE.ABSOLUTE; 
    
    @Override
    public void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         browseToRoot();
    } 
    
    /**
     * goes back to the sdcard directory
     */
    private void browseToRoot() {
        browseTo(new File("/sdcard"));
  	} 
    
    /**
     * goes back one level of not at the root of the sdcard
     */
    private void upOneLevel(){
        if(this.currentDirectory.getParent() != null)
             this.browseTo(this.currentDirectory.getParentFile());
   } 
    
    private void browseTo(final File aDirectory){
        if (aDirectory.isDirectory()){
             this.currentDirectory = aDirectory;
             fill(aDirectory.listFiles());
        }else{
             OnClickListener okButtonListener = new OnClickListener(){
                  // @Override
                  public void onClick(DialogInterface dialog, int arg1) {
					Bundle data = new Bundle();
			        data.putString("FILE_PATH", aDirectory.getAbsolutePath());
					Intent i = new Intent();
		            i.putExtras(data);
					setResult(RESULT_OK, i);
					finish();
                  }
             };
             OnClickListener cancelButtonListener = new OnClickListener(){
                  // @Override
                  public void onClick(DialogInterface arg0, int arg1) {
                       // Do nothing
                  }
             };
             new AlertDialog.Builder(this).setTitle("open file?")
             .setMessage("Open "+aDirectory.getName())
             .setPositiveButton("OK", okButtonListener)
             .setNegativeButton("Cancel", cancelButtonListener)
             .show();
        }
   } 
    private void fill(File[] files) {
        this.directoryEntries.clear();
        
        // Add the "." and the ".." == 'Up one level'
        try {
             Thread.sleep(10);
        } catch (InterruptedException e1) {
             // TODO Auto-generated catch block
             e1.printStackTrace();
        }
        this.directoryEntries.add(".");
        
        if(this.currentDirectory.getParent() != null)
             this.directoryEntries.add("..");
        
        switch(this.displayMode){
             case ABSOLUTE:
                  for (File file : files){
                       this.directoryEntries.add(file.getPath());
                  }
                  break;
             case RELATIVE: // On relative Mode, we have to add the current-path to the beginning
                  int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();
                  for (File file : files){
                       this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
                  }
                  break;
        }
        
        ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                  R.layout.file_row, this.directoryEntries);
        
        this.setListAdapter(directoryList);
   }

   @Override
   protected void onListItemClick(ListView l, View v, int position, long id) {
        String selectedFileString = this.directoryEntries.get(position);
        if (selectedFileString.equals(".")) {
             // Refresh
             this.browseTo(this.currentDirectory);
        } else if(selectedFileString.equals("..")){
             this.upOneLevel();
        } else {
             File clickedFile = null;
             switch(this.displayMode){
                  case RELATIVE:
                       clickedFile = new File(this.currentDirectory.getAbsolutePath()
                                                          + this.directoryEntries.get(position));
                       break;
                  case ABSOLUTE:
                       clickedFile = new File(this.directoryEntries.get(position));
                       break;
             }
             if(clickedFile != null)
                  this.browseTo(clickedFile);
        }
   }
}